<template>
    <div class="user-resource-tree">
        <yh-dialog drag title="菜单权限" :visible="visibleTemp" @close="closeModal" :close-on-click-modal="false">
            <div class="dialog-main">
                <el-tree
                    :data="treeData"
                    show-checkbox
                    node-key="resourceCode"
                    ref="tree"
                    :default-checked-keys="checkedKeys"
                    highlight-current
                    :props="defaultProps"
                    :key="refresh + 'refreshTree'"
                />
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="closeModal">取 消</el-button>
                <el-button size="mini" type="primary" @click="onSubmit" v-if="!$attrs.isDisabled">确 定</el-button>
            </div>
        </yh-dialog>
    </div>
</template>

<script lang="ts">
import { Component, Emit, Prop, PropSync, Vue, Watch } from 'vue-property-decorator';
import { addRoleResources, getAllMenu, getRoleResourceList } from '../api';
import { getUser } from '@/utils/user-util';
@Component({ name: 'UserResourceTree' })
export default class UserResourceTree extends Vue {
    @PropSync('visible') syncVisible: boolean;
    @Prop({ default: '' }) code: string;

    private refresh = 0;
    private visibleTemp = false;
    private defaultProps = {
        label: 'resourceName',
        children: 'children',
    };

    private treeData = [];
    private myCodeList = [];
    // 所有子数据
    private childrenCodes = [];
    // 已选中的数据
    private checkedKeys = [];
    showTreeData() {
        const isDisabled = this.$attrs.isDisabled;
        console.log(isDisabled, 'isDisabled');
        const data = JSON.parse(JSON.stringify(this.treeData));
        this.setDisabled1(data);
        if (isDisabled) {
            this.setDisabled(data);
        }
        return data;
    }

    // 递归函数，给每层树赋值disabled
    setDisabled(treeData) {
        treeData.forEach(item => {
            this.$set(item, 'disabled', true);
            if (item.children) {
                this.setDisabled(item.children);
            }
        });
        return treeData;
    }

    setDisabled1(treeData) {
        treeData.forEach(item => {
            if (!this.myCodeList.includes(item.resourceCode)) {
                this.$set(item, 'disabled', true);
            }
            if (item.children) {
                this.setDisabled1(item.children);
            }
        });
        return treeData;
    }

    mounted() {
        if (getUser().resources.length > 0) {
            this.myCodeList = getUser().resources.map(item => item.resourceCode);
        }
        getAllMenu().then(response => {
            response = response || [];
            this.treeData = response;
            let childrenCodes = [];
            this.getMenuList(response, childrenCodes);
            this.childrenCodes = childrenCodes;
        });
    }

    /**
     * 获取下级菜单/或按钮 即排除所有父资源
     */
    getMenuList(data, menuAll) {
        for (let item of data) {
            if (item.children && item.children.length > 0) {
                this.getMenuList(item.children, menuAll);
            } else {
                menuAll.push(item.resourceCode);
            }
        }
    }

    // 获取选中 code
    getSelectedCode() {
        getRoleResourceList(this.code).then(response => {
            response = response || [];
            let checkedKeys = response.filter(item => this.childrenCodes.includes(item));
            this.checkedKeys = checkedKeys;
            this.refresh++;
        });
    }

    @Watch('visible')
    onWatchVisible(value) {
        if (value !== this.visibleTemp && value) {
            this.visibleTemp = value;
            this.treeData = this.showTreeData();
            this.getSelectedCode();
        } else {
            this.visibleTemp = value;
        }
    }

    // 关闭弹窗
    closeModal() {
        this.syncVisible = false;
    }

    onSubmit() {
        let tree = this.$refs.tree as any;
        let checkedKeys = tree.getCheckedKeys() || [];
        let halfCheckedKeys = tree.getHalfCheckedKeys() || [];
        const data = [...checkedKeys, ...halfCheckedKeys];

        addRoleResources({
            roleCode: this.code,
            resourceCodes: data,
            serialNo: this.$attrs.serialNo,
        }).then(res => {
            this.yh_message_success('修改成功');
            this.$emit('menu-setting');
            this.closeModal();
        });
    }

    @Emit('on-submit')
    onEmitSubmit(data): any[] {
        return data;
    }
}
</script>

<style lang="scss" scoped>
.user-resource-tree /deep/ .el-dialog__body {
    height: 400px;
    max-height: none;
}
</style>
